<?php

namespace app\api\controller;

use app\BaseController;
use think\facade\View;
use think\facade\Config;
// use think\facade\Session;
use app\common\model\SystemAdmin;
use app\common\model\Store;
use app\common\model\YearCard;
use app\common\model\User;
use app\common\controller\Handle;
use GatewayWorker\Lib\Gateway;
use app\common\model\Copyright;
use app\common\model\Client;
use app\common\model\Material;
use app\common\model\Product;
use app\common\model\Order;
use app\common\model\Help;
use app\common\model\ProductBargain;

class ApiUser extends ApiBase
{
    public function initialize()
    {
        parent::initialize();
        $this->systemadmin = new SystemAdmin;
        $this->user = new User;
        $this->Store = new Store;
        $this->YearCard = new YearCard;
        $this->Client = new Client;
        $this->Material = new Material;
        $this->Product = new Product;
        $this->Order = new Order;
        $this->Help = new Help;
        $this->ProductBargain = new ProductBargain;
    }
    public function getUser()
    {
        $user =  $this->user->getOne(['id' => $this->uid], 'nickname,headimg,number,sex,phone,store_id,identity,name');
        $user['headimg'] = 'https://' . Config::get('sysconfig')['api_domain'] . $user['headimg'] ?: "/system/default.png";
        return json(['status' => 1, 'data' => $user]);
    }
    // 用户更换头像
    public function uploadImg()
    {
        $file = request()->file('file');
        if (!$file) {
            return ['status' => 0, 'msg' => '上传失败，name不存在'];
        }
        $user =  $this->user->getOne(['id' => $this->uid], 'headimg');

        // 获取文件原始扩展名
        $extension = $file->getClientOriginalExtension();

        $hand = new Handle();

        $dirname = "api_headimg";

        $savename = $hand->qiniuImg("file", $dirname);

        $add['file_name'] = $savename['fileName'];
        $add['upload_type'] = 2;
        $add['file_path'] = $savename['url'];
        $add['file_type'] = $extension;
        $add['ip'] = Request::ip();
        $add['add_time'] = time();
        $add['user_id'] = $this->uid;
        
        $res = $this->FileLog->create($add);
        $fileLogId = $res->id;
        $savename['file_id'] = $fileLogId;

        $this->user->where(['id' => $this->uid])->update(['headimg' => $savename['fileName']]);

        return  json($savename);

      
    }
    // 用户更换昵称
    public function setNickName()
    {
        $post = request()->post();
        $this->user->where(['id' => $this->uid])->update(['nickname' => $post['nickname']]);
        return json(['status' => 1, 'msg' => '修改成功']);
    }

    // 用户基本信息修改
    public function setUserContent()
    {
        
        $post = request()->post();

        $save = [];
        if(!empty($post['name'])){
            $save['name'] = $post['name'];
        }

        if(!empty($post['sex'])){
            $save['sex'] = $post['sex'];
        }

        if(!empty($post['phone'])){
            $save['phone'] = $post['phone'];
        }

        if(empty($save)){
            return json(['status' => 0, 'msg' => '请上次要修改的信息']);
        }

        $this->user->where(['id' => $this->uid])->update($save);
        
        return json(['status' => 1, 'msg' => '修改成功']);

    }

    // 激活年卡
    public function activateYearCard()
    {
        $post = request()->post();

        if(empty($post['cord_number'])){
            return json(['status' => 0, 'msg' => '请上传卡号']);
        }


        $card = $this->YearCard->where(['number'=>$post['cord_number']])->find();


        if(empty($card)){
            return json(['status' => 0, 'msg' => '卡号错误']);
        }

        if($card['status'] == 1){
            return json(['status' => 0, 'msg' => '年卡已经使用']);
        }

        $user =  $this->user->getOne(['id' => $this->uid], 'nickname,headimg,number,sex,phone,store_id,identity,name');
        if($user['identity'] == 2){
            return json(['status' => 0, 'msg' => '店员不能激活年卡']);
        }

        if($user['identity'] == 1 && !empty($user['store_id'])){
            $store = $this->Store->getOne(['id'=>$user['store_id'],"id,name,expiration_time,status"]);

            if($store['status'] == 1){
                return json(['status' => 0, 'msg' => '您店铺已经被禁用']);
            }

            if($stroe['expiration_time']  > time()){
                $currentTimestamp  = $stroe['expiration_time'];
            }else{
                $currentTimestamp  =  time();
            }

            $save['expiration_time'] = strtotime('+1 year', $currentTimestamp);
            $this->Store->where(['id' => $user['store_id']])->update($save);
            $this->YearCard->where(['id' => $card['id']])->update(['status'=>1]);
        
            return json(['status' => 1, 'msg' => '激活成功']);
        }else{
            $add = [
                "expiration_time" => strtotime('+1 year', time()),
                "name" => "我的店铺",
                "created_at" =>date("Y-m-d H:i:s"),
                "updated_at" =>date("Y-m-d H:i:s"),
            ];

            $store = $this->Store->create($add);
            $store_number = 100000000+ $store->id;
            $store_id = $store->id;

            $this->Store->where(['id' => $store_id])->update(['number'=>$store_number]);
            $this->user->where(['id' => $this->uid])->update(['store_id'=>$store_id,'store_number'=>$store_number,"identity"=>1]);
            
            $this->YearCard->where(['id' => $card['id']])->update(['status'=>1]);
        
            return json(['status' => 1, 'msg' => '激活成功']);
        }

    }

    // 客服电话
    public function phone()
    {
        $data = Config::get('sysconfig');

        $phone = $data['admin_phone'];

        return json(['status' => 1, 'msg' => '查询成功',"phone"=>$phone]);
    }

     // 专属banner
     public function banner()
     {
         
        // 存储空间对应的域名
        $domain = config('sysconfig.qiniu_domain');
         $data = Config::get('sysconfig');
        
         if(!empty($data['banner'])){
            $banner = $data['banner'];
         }else{
            $banner = "";
         }
         
 
         return json(['status' => 1, 'msg' => '查询成功',"banner"=>$banner]);
     }


    // 版权声明
    public function copyright()
    {
        $one =  Copyright::where(["id"=>1])->find();

        return json(['status' => 1, 'msg' => '查询成功',"data"=>$one]);
    }   


    // 订单数据
    public function orderData()
    {
         // 判断店铺是否正常
         $is_store = $this->storeIsNormal($this->uid);
 
         if($is_store['code'] == 1){
           $data = [
               "order_num"=>0,
               "direct_order_num"=>0,
               "referral_order_num"=>0,
               "cross_order_num"=>0,
           ];
         }else{
           
            $order_num = 0;
            $direct_order_num = 0;
            $referral_order_num = 0;
            $cross_order_num = 0;

            $store_id = $is_store['store_id'];
            $year =date("Y");
            $month =date("m");
            $list = $this->Order->where(['store_id'=> $store_id,"YYY"=>$year,"MMM"=>$month])->select();

            foreach($list as $key=>$val){
                switch($val['type']){
                    case 1:
                        $order_num ++;
                        $direct_order_num ++;
                        break;
                    case 2:
                        $order_num ++;
                        $direct_order_num ++;
                        break;
                    case 3:
                        $order_num ++;
                        $referral_order_num ++;
                        break;
                    case 4:
                        $order_num ++;
                        $cross_order_num ++;
                        break;
                    case 5:
                        $order_num ++;
                        $direct_order_num ++;
                        break;
                    case 6:
                        $order_num ++;
                        $direct_order_num ++;
                        break;
                    case 8:
                        $order_num ++;
                        $direct_order_num ++;
                        break;
                }
            }


            $data = [
                "order_num"=>$order_num,
                "direct_order_num"=>$direct_order_num,
                "referral_order_num"=>$referral_order_num,
                "cross_order_num"=>$cross_order_num,
            ];

            
         }
         return json(['status' => 1, 'msg' => '查询成功',"data"=>$data]);
        
  
    }

    // 店铺数据
    public function  storeData()
    {

         // 判断店铺是否正常
         $is_store = $this->storeIsNormal($this->uid);
 
         if($is_store['code'] == 1){
           $data = [
               "order_num"=>0,
               "product_num"=>0,
               "client_num"=>0,
               "material_num"=>0,
           ];
         }else{

            $store_id = $is_store['store_id'];
            $order_num = $this->Order->where(['store_id'=> $store_id,"YYY"=>date("Y")])->count();
            $product_num = $this->Product->where(['store_id'=> $store_id])->count();
            $client_num = $this->Client->where(['store_id'=> $store_id])->count();
            $material_num = $this->Material->where(['store_id'=> $store_id])->count();

            $data = [
                "order_num"=>$order_num,
                "product_num"=>$product_num,
                "client_num"=>$client_num,
                "material_num"=>$material_num,
            ];

        }

        return json(['status' => 1, 'msg' => '查询成功',"data"=>$data]);
    }


    // 使用说明列表
    public function helpList()
    {
        $list =  Help::select();

        return json(['status' => 1, 'msg' => '查询成功',"data"=>$list]);
    }

     // 使用说明详情
     public function getHelp()
     {


         $one =  Help::where(["id"=>1])->find();

         // 存储空间对应的域名
        $domain = config('sysconfig.qiniu_domain');


        if($one['type'] == 1){
            $one->video_url = $one['video_url'];
        }
 
         return json(['status' => 1, 'msg' => '查询成功',"data"=>$one]);
     }   



      // 砍一刀列表
    public function bargainList()
    {
         // 存储空间对应的域名
         $domain = config('sysconfig.qiniu_domain');

         // 判断店铺是否正常
        $is_store = $this->storeIsNormal($this->uid);

        if($is_store['code'] == 1){
            return json(['status' => 0, 'msg' =>$is_store['msg']]);
        }

        $store_id = $is_store['store_id'];

        
 
         if(empty($data['limit'])){
             $data['limit'] = 10;
         }
 
         if(empty($data['page'])){
             $data['page'] = 1;
         }
 
         $list = $this->ProductBargain->getPagelist(["deleted_at"=>null,"store_id"=> $store_id],"","");
 
        //  foreach($list as $key=>$val){
        //     $list[$key]['logo'] = $domain."/".$val['logo'];
        //  }
 
         $count = $this->ProductBargain->countRows(['user_id'=>$this->uid,"deleted_at"=>null]);
 
         $pages = ceil($count/$data['limit']);
 
         return json(['status'=> 1,'data'=>$list,'pages'=>$pages,"count"=>$count]);
    }

    // 砍一刀详情
    public function bargainGet()
    {
         // 存储空间对应的域名
         $domain = config('sysconfig.qiniu_domain');

         $data = request()->post();

        // 判断店铺是否正常
        $is_store = $this->storeIsNormal($this->uid);

        if($is_store['code'] == 1){
            return json(['status' => 0, 'msg' =>$is_store['msg']]);
        }

        $store_id = $is_store['store_id'];

        if(empty($data['bargain_id'])){
            return json(['status' => 0, 'msg' =>"请上传砍一刀id"]);
        }
 
        $list = $this->ProductBargain->getOne(['id' =>$data['bargain_id'],'deleted_at'=>null]);

        if(empty($list)){
            return json(['status' => 0, 'msg' =>"砍单不存在"]);
        }

         
        // $list['logo'] = $domain."/".$list['logo'];
 
 
         $list['content'] = str_replace("api_project",$domain."/api_project",$list['content']);
 
        
 
         return json(['status'=> 1,'data'=>$list]);
    }


    // 核销砍一刀订单
    public function cancelBargain()
    {
        // 判断店铺是否正常
        $is_store = $this->storeIsNormal($this->uid);

        $data = request()->post();

        if($is_store['code'] == 1){
            return json(['status' => 0, 'msg' =>$is_store['msg']]);
        }

        $store_id = $is_store['store_id'];

        if(empty($data['bargain_id'])){
            return json(['status' => 0, 'msg' =>"请上传砍一刀id"]);
        }

        $list = $this->ProductBargain->getOne(['id' =>$data['bargain_id'],'deleted_at'=>null]);

        if(empty($list)){
            return json(['status' => 0, 'msg' =>"砍单不存在"]);
        }

        $res = $this->ProductBargain->where(['id' =>$data['bargain_id'],'deleted_at'=>null])->update(['status'=>2]);

        return json(['status' => 1, 'msg' => '操作成功']);
  
    }
 
}
